/**
 * 
 */
package admin.mode;

import java.util.ArrayList;
import java.util.HashMap;

import base.PageList;
import base.Power;

/**
 * @author qsj
 * 
 */
public class UserMode {
	@SuppressWarnings("unchecked")
	public ArrayList getRoleList(Power power, AdminMode admin) throws Exception {
		String sql = "select * from houseclub_role";
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public HashMap getRoleById(Power power, String role_id) throws Exception {
		String sql = "select * from houseclub_role where role_id=" + role_id;
		return power.getMapFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public ArrayList getRolePermByRoleId(Power power, String role_id)
			throws Exception {
		String sql = "select * from houseclub_role_permission where role_id="
				+ role_id;
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public boolean roleSave(Power power, AdminMode admin) throws Exception {
		String role_name = power.getParameter("role_name");
		String sort = power.getParameter("sort");
		String is_super = power.getParameter("is_super");
		String[] perms = power.getRequest().getParameterValues("perms");
		ArrayList permsList = splitPerms(perms);
		String sql = "insert into houseclub_role (role_name,sort,is_super) values ('"
				+ role_name + "'," + sort + "," + is_super + ")";
		if (power.executeUpdate(sql) > -1) {
			String lastId = power.getMapFromSql("SELECT LAST_INSERT_ID() id")
					.get("ID").toString();
			rolePermsDeleteByRoleId(power, lastId);
			for (int i = 0; i < permsList.size(); i++) {
				rolePermsSave(power, lastId, permsList.get(i).toString());
			}
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public boolean roleUpdate(Power power, AdminMode admin) throws Exception {
		String role_id = power.getParameter("role_id");
		String role_name = power.getParameter("role_name");
		String sort = power.getParameter("sort");
		String is_super = power.getParameter("is_super");
		String[] perms = power.getRequest().getParameterValues("perms");
		ArrayList permsList = splitPerms(perms);
		String sql = "update houseclub_role set role_name='" + role_name
				+ "',sort=" + sort + ",is_super=" + is_super
				+ " where role_id=" + role_id;
		if (power.executeUpdate(sql) > -1) {
			rolePermsDeleteByRoleId(power, role_id);
			for (int i = 0; i < permsList.size(); i++) {
				rolePermsSave(power, role_id, permsList.get(i).toString());
			}
			return true;
		}
		return false;
	}

	public boolean roleDelete(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "delete from houseclub_role where role_id in(" + str + ")";
		if (power.executeUpdate(sql) > -1) {
			for (int i = 0; i < ids.length; i++) {
				rolePermsDeleteByRoleId(power, ids[i]);
			}
			return true;
		}
		return false;
	}

	public boolean rolePermsDeleteByRoleId(Power power, String roleId)
			throws Exception {
		String sql = "delete from houseclub_role_permission where role_id="
				+ roleId;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean rolePermsSave(Power power, String roleId, String uri)
			throws Exception {
		String sql = "insert into houseclub_role_permission (role_id,uri) values ("
				+ roleId + ",'" + uri + "')";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	private ArrayList splitPerms(String[] perms) {
		ArrayList list = new ArrayList();
		if (perms != null) {
			for (String perm : perms) {
				for (String p : perm.split(",")) {
					if (p != null && !p.equals("")) {
						list.add(p);
					}
				}
			}
		}
		return list;
	}

	// 用户组
	@SuppressWarnings("unchecked")
	public ArrayList getGroupList(Power power, AdminMode admin)
			throws Exception {
		String sql = "select * from houseclub_group";
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public ArrayList getGroupPermByGroupId(Power power, String group_id)
			throws Exception {
		String sql = "select * from houseclub_group_permission where group_id="
				+ group_id;
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public HashMap getGroupById(Power power, String group_id) throws Exception {
		String sql = "select * from houseclub_group where group_id=" + group_id;
		return power.getMapFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public boolean groupSave(Power power, AdminMode admin) throws Exception {
		String group_name = power.getParameter("group_name");
		String sort = power.getParameter("sort");
		String is_super = power.getParameter("is_super");
		String[] perms = power.getRequest().getParameterValues("perms");
		ArrayList permsList = splitPerms(perms);
		String sql = "insert into houseclub_group (group_name,sort,is_super) values ('"
				+ group_name + "'," + sort + "," + is_super + ")";
		if (power.executeUpdate(sql) > -1) {
			String lastId = power.getMapFromSql("SELECT LAST_INSERT_ID() id")
					.get("ID").toString();
			groupPermsDeleteByGroupId(power, lastId);
			for (int i = 0; i < permsList.size(); i++) {
				groupPermsSave(power, lastId, permsList.get(i).toString());
			}
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public boolean groupUpdate(Power power, AdminMode admin) throws Exception {
		String group_id = power.getParameter("group_id");
		String group_name = power.getParameter("group_name");
		String sort = power.getParameter("sort");
		String is_super = power.getParameter("is_super");
		String[] perms = power.getRequest().getParameterValues("perms");
		ArrayList permsList = splitPerms(perms);
		String sql = "update houseclub_group set group_name='" + group_name
				+ "',sort=" + sort + ",is_super=" + is_super
				+ " where group_id=" + group_id;
		if (power.executeUpdate(sql) > -1) {
			groupPermsDeleteByGroupId(power, group_id);
			for (int i = 0; i < permsList.size(); i++) {
				groupPermsSave(power, group_id, permsList.get(i).toString());
			}
			return true;
		}
		return false;
	}

	public boolean groupDelete(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "delete from houseclub_group where group_id in(" + str
				+ ")";
		if (power.executeUpdate(sql) > -1) {
			for (int i = 0; i < ids.length; i++) {
				groupPermsDeleteByGroupId(power, ids[i]);
			}
			return true;
		}
		return false;
	}

	public boolean groupPermsDeleteByGroupId(Power power, String groupId)
			throws Exception {
		String sql = "delete from houseclub_group_permission where group_id="
				+ groupId;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean groupPermsSave(Power power, String groupId, String uri)
			throws Exception {
		String sql = "insert into houseclub_group_permission (group_id,uri) values ("
				+ groupId + ",'" + uri + "')";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public HashMap getMemberList(Power power, AdminMode admin) throws Exception {
		String sql = "select * from houseclub_user a left join (select ugr.user_id,g.group_name from houseclub_user_group_role ugr,houseclub_group g where g.group_id=ugr.group_id) b on a.userid=b.user_id";
		PageList PL = new PageList();
		PL.setOnePage(20);
		PL.setEndForm(true);
		ArrayList list = new ArrayList();
		String sqlList = PL.getPageNums(power, sql.toString());
		list = power.getListFromSql(sqlList);
		power.debug(sqlList);
		HashMap map = new HashMap();
		map.put("list", list);
		map.put("PL", PL.getContent());
		map.put("PLend", PL.getEndButtonString());
		return map;
	}

	public boolean memberSave(Power power, AdminMode admin) throws Exception {
		String username = power.getParameter("username");
		String email = power.getParameter("email");
		String password = power.getParameter("password");
		// MD5Util cipher = new MD5Util();
		// password = cipher.generatePassword(password);
		String groupId = power.getParameter("groupId");
		String roleId = power.getParameter("roleId");
		String realname = power.getParameter("realname");
		// String gender = power.getParameter("gender");
		String telephone = power.getParameter("telephone");
		String sql = "insert into houseclub_user set username='" + username
				+ "',email='" + email + "',password='" + password
				+ "',realname='" + realname + "',telephone='" + telephone + "'";
		if (power.executeUpdate(sql) > -1) {
			String lastId = power.getMapFromSql("SELECT LAST_INSERT_ID() id")
					.get("ID").toString();
			if (roleId.equals("0")) {// 非后台用户
				saveUserGroupRole(power, lastId, groupId);
			} else {
				saveUserGroupRole(power, lastId, groupId, roleId);
			}

			return true;
		}
		return false;
	}

	public boolean memberUpdate(Power power, AdminMode admin) throws Exception {
		String userid = power.getParameter("userid");
		// String username = power.getParameter("username");
		String email = power.getParameter("email");
		String password = power.getParameter("password");
		// if(!password.equals("")){
		// MD5Util cipher = new MD5Util();
		// password = cipher.generatePassword(password);
		// }

		String groupId = power.getParameter("groupId");
		String roleId = power.getParameter("roleId");
		String realname = power.getParameter("realname");
		// String gender = power.getParameter("gender");
		String telephone = power.getParameter("telephone");
		// String sql =
		// "update houseclub_user set username='"+username+"',email='"+email+"',userpassword='"+password+"',realname='"+realname+"',sex='"+gender+"' where userid="+userid;
		String sql = "update houseclub_user set "
				+ (password.equals("") ? "" : "password='" + password + "',")
				+ "email='" + email + "',realname='" + realname
				+ "',telephone='" + telephone + "' where userid=" + userid;

		if (power.executeUpdate(sql) > -1) {
			if (roleId.equals("0")) {// 非后台用户
				updateUserGroupRole(power, userid, groupId);
			} else {
				updateUserGroupRole(power, userid, groupId, roleId);
			}
			return true;
		}
		return false;
	}

	// 无后台权限
	public boolean updateUserGroupRole(Power power, String userid,
			String groupid) throws Exception {
		String sql = "update houseclub_user_group_role set group_id=" + groupid
				+ ",is_admin=0 where user_id=" + userid;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	// 有后台权限
	public boolean updateUserGroupRole(Power power, String userid,
			String groupid, String roleid) throws Exception {
		String sql = "update houseclub_user_group_role set group_id=" + groupid
				+ ",role_id=" + roleid + ",is_admin=1 where user_id=" + userid;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	// 无后台权限
	public boolean saveUserGroupRole(Power power, String userid, String groupid)
			throws Exception {
		String sql = "insert into houseclub_user_group_role set group_id="
				+ groupid + ",is_admin=0, user_id=" + userid;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	// 有后台权限
	public boolean saveUserGroupRole(Power power, String userid,
			String groupid, String roleid) throws Exception {
		String sql = "insert into houseclub_user_group_role set group_id="
				+ groupid + ",role_id=" + roleid + ",is_admin=1, user_id="
				+ userid;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public HashMap getMember(Power power) throws Exception {
		String userid = power.getParameter("id");
		String sql = "select * from houseclub_user a, houseclub_user_group_role b where a.userid=b.user_id and a.userid="
				+ userid;
		return power.getMapFromSql(sql);

	}

	public boolean memberDelete(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "delete from houseclub_user where userid in(" + str + ")";
		if (power.executeUpdate(sql) > -1) {
			for (int i = 0; i < ids.length; i++) {
				deleteUserGroupRoleByUesrId(power, ids[i]);
			}
			return true;
		}
		return false;
	}

	public boolean deleteUserGroupRoleByUesrId(Power power, String userid)
			throws Exception {
		String sql = "delete from houseclub_user_group_role where user_id="
				+ userid;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean updaterole(Power power) throws Exception {
		String witch = power.getParameter("witch");
		String role = power.getParameter("role");
		String num = power.getParameter("num");
		double number = Double.parseDouble(num);
		String sql = "";
		if ("user".equals(witch)) {
			sql = "update  hc_user_count set role = '" + role + "' ,num = "
					+ number + "  where witch='" + witch + "'";
		}
		if ("house".equals(witch)) {
			sql = "update  hc_user_count  set role = '" + role + "' ,num = "
					+ number + "  where witch='" + witch + "'";
		}

		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public void selectrole(Power power) throws Exception {
		// 查询用户数和店铺数
		String sqlcountu = "select count(*) as count from houseclub_user";
		String sqlcounth = "select count(*) as count from hc_shop";
		HashMap<String, String> mapcountu = power.getMapFromSql(sqlcountu);
		HashMap<String, String> mapcounth = power.getMapFromSql(sqlcounth);
		// 查询当前计算规则
		String sqlroleu = "select * from hc_user_count where witch = 'user'";
		String sqlroleh = "select * from hc_user_count where witch = 'house'";
		HashMap<String, String> maproleu = role(power, power.getMapFromSql(sqlroleu));
		HashMap<String, String> maproleh = role(power, power.getMapFromSql(sqlroleh));
		// 用户数
		String usercount = mapcountu.get("COUNT").toString();
		// 店铺数
		String housecount = mapcounth.get("COUNT").toString();
		power.setAttribute("usercount", usercount);
		power.setAttribute("housecount", housecount);
		power.setAttribute("maproleu", maproleu);
		power.setAttribute("maproleh", maproleh);

	}

	public HashMap<String, String> role(Power power, HashMap<String, String> map)
			throws Exception {
		String role = map.get("ROLE").toString();
		if ("1".equals(role)) {
			map.put("role_change", "加");
		} else if ("2".equals(role)) {
			map.put("role_change", "减");
		} else if ("3".equals(role)) {
			map.put("role_change", "乘");
		} else if ("4".equals(role)) {
			map.put("role_change", "除");
		}
		return map;
	}
}
